package com.example.demo.entity;

import com.fasterxml.jackson.annotation.JsonBackReference; // 导入注解
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.ToString;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "bookkeeping")
// EqualsAndHashCode 和 ToString 已经排除了 user
@EqualsAndHashCode(exclude = "user")
@ToString(exclude = "user")
public class Bookkeeping {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false)
    @JsonBackReference // 添加此注解，表示这是关系的反向端（子端），在序列化时不会再次序列化其引用的User对象的bookkeepingRecords
    private User user;

    @Column(name = "type")
    private Integer type; // 0: 收入 1: 支出

    @Column(name = "book_date")
    private LocalDate bookDate;

    @Column(name = "category", length = 255)
    private String category;

    @Column(name = "price", precision = 10, scale = 2)
    private BigDecimal price;

    @Column(name = "remark", length = 255)
    private String remark;

    @CreationTimestamp
    @Column(name = "add_time", updatable = false)
    private LocalDateTime addTime;

    @UpdateTimestamp
    @Column(name = "update_time")
    private LocalDateTime updateTime;

    @Column(name = "year")
    private Integer year;

    @Column(name = "month")
    private Integer month;

    @PrePersist
    @PreUpdate
    public void prePersistOrUpdate() {
        if (bookDate != null) {
            this.year = bookDate.getYear();
            this.month = bookDate.getMonthValue();
        }
    }
}
